
/**
*┌──────────────────────────────────────────────────────────────┐
*│　描    述：用户支付出入金记录                                                    
*│　作    者：gaotang                                            
*│　版    本：1.0    模板代码自动生成                                                
*│　创建时间：2019-02-27 16:50:41                             
*└──────────────────────────────────────────────────────────────┘
*┌──────────────────────────────────────────────────────────────┐
*│　命名空间： BestTrader.Cms.Services                                  
*│　类    名： UCAlipayInCashService                                    
*└──────────────────────────────────────────────────────────────┘
*/
using BestTrader.Cms.Core.Extensions;
using BestTrader.Cms.IRepository;
using BestTrader.Cms.IServices;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using BestTrader.Cms.Models;
using BestTrader.Cms.ViewModels;
using AutoMapper;
using BestTrader.Cms.Core.Options;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Threading.Tasks;
using BestTrader.Cms.RmmfSoftServices;

namespace BestTrader.Cms.Services
{
    public class UCAlipayInCashService: IUCAlipayInCashService
    {
        private readonly RmmfSoftAccountService _rmmfAccountService;
        private readonly RmmfSoftCashService _rmmfCashService;
        
        private readonly YunPayClientService _payService;
        private readonly IUCInOutCashRepository _inoutCashrepository;
        private readonly IUCAlipayInCashRepository _repository;
        private readonly IMapper _mapper;
        private readonly ILogger<UCAlipayInCashService> _logger;

        public UCAlipayInCashService(RmmfSoftAccountService rmmfAccountService
            , RmmfSoftCashService rmmfCashService
            , YunPayClientService payService
            , IUCAlipayInCashRepository repository
            , IUCInOutCashRepository inoutCashrepository
            , IMapper mapper
            , ILogger<UCAlipayInCashService> logger)
        {
            _rmmfAccountService = rmmfAccountService;
            _rmmfCashService = rmmfCashService;
            _payService = payService;
            _repository = repository;
            _inoutCashrepository = inoutCashrepository;
            _mapper = mapper;
            _logger = logger;
        }

        public QRCodeModel AddYunpayQRCode(ConfirmInCashModel item, string ip4, string userId)
        {
            var result = default(QRCodeModel);
            if (item != null)
            {
                // 支付方式：支付宝，且不为空(人民币)
                if (item.CashModel == 2 && item.RMBMoney.HasValue) {
                    var _money = item.RMBMoney.HasValue ? item.RMBMoney.Value : 0;
                    // 处理数据为两位小数
                    var rmbMoney = Math.Round(_money, 2);
                    var json = _payService.GetYunPayData(item.OrderNo, rmbMoney, ip4).Result;

                    result = JsonConvert.DeserializeObject<QRCodeModel>(json);
                    if (result != null)
                    {
                        if (!string.IsNullOrEmpty(result.times))
                        {
                            // 转换PHP相关的时间Time()
                            var aa = new DateTime(1970, 1, 1);
                            long a = (DateTime.Now.Ticks - aa.Ticks) / 10000000 - 8 * 60 * 60;
                            result.times = $"{long.Parse(result.times) - a}";
                        }
                        // 同步支付宝入金记录
                        var now = DateTime.Now;

                        var entity = _mapper.Map<UCAlipayInCash>(result);
                        entity.UCAlipayInCashId = item.Id;
                        entity.IP4 = ip4;
                        entity.Code = entity.State == 1 ? 0 : 3;
                        entity.AddManagerId = userId.ToInt32() ?? 0;
                        entity.IsDelete = false;
                        entity.AddTime = now;

                        if (_repository.Insert(entity) > 0)
                        {
                            //item.QRCode = result.qrcode;
                            item.QRCode = $"/images/alipay/alipay.jpg?_t={DateTime.Now.ToBinary()}";

                            var usdMoneys = new Decimal[] { 100, 500, 1000, 2000, 3000, 4000, 5000, 6000, 1500, 2500, 3500, 4500, 5500 };
                            //var usdMoneys = new Decimal[] { 100, 500, 1000,1500,2000, 3000, 4000, 5000, 6000 };

                            // 生成支付宝相关的规则  
                            // var uMoney = Math.Floor(_money / 7.75M / 1.005M);
                            var uMoney = Math.Round(_money / 7.75M / 1.005M, 0);
                            if (usdMoneys.Contains(uMoney))
                            {
                                //var _current = Math.Round(_money * 1.005M, 3).ToString();
                                //var imgSrc = $"{ _current.Substring(0, _current.IndexOf('.') + 2) }{(DateTime.Now.Minute / 6)}";
                                //item.QRCode = $"/images/alipay/{imgSrc}.jpg";
                                item.QRCode = $"/images/alipay/{Math.Round(item.RMBMoney??0, 2)}.jpg?_t={DateTime.Now.ToBinary()}";
                            }
                            item.Times = result.times;
                        }
                    }
                }
                    
            }
            return result;
        }

        /// <summary>
        /// 确认订单
        /// </summary>]
        public void ConfirmAliPayOrder(ConfirmAliPayOrderModel model)
        {
            if (model == null)
            {
                _logger.LogError("第三方支付信息：订单不存在！");
                return;
            }
            if (model.name.IsNullOrWhiteSpace())
            {
                _logger.LogError("第三方支付信息：网站单号/支付宝备注不存在！");
                var msg = $" 支付宝/微信/QQ钱包交易单号:{ model.ddh }   支付金额:{ model.money }     支付类型 1支付宝，2QQ钱包，3微信:{model.lb }   网站单号/支付宝备注:{ model.name }   KEY密匙：{ model.key }   支付成功日期：{ model.paytime }";
                _logger.LogError(msg);
                return;
            }

            var entity = _repository.Get($"select top 1 * from UCAlipayInCash where Data='{ model.name }'");
            if (entity == null)
            {
                _logger.LogError($"第三方支付信息：本地数据库[UCAlipayInCash]不存在相关订单信息【{ model.name }】！");
                return;
            }

            var inOutEntity = _inoutCashrepository.Get(entity.UCAlipayInCashId);
            if (inOutEntity == null)
            {
                _logger.LogError($"第三方支付信息：本地数据库[UCInOutCash]不存在相关订单信息【{ model.name }】！");
                return;
            }

            // 如果第三支付的订单金额与数据库不一样，更新本地数据库数据
            if (model.money >= inOutEntity.RMBMoney)
            {
                inOutEntity.State = 1;
                inOutEntity.Remark = "用户入金(充值成功)";
            }
            else {
                inOutEntity.State = 0;
                inOutEntity.Remark = "用户入金(小于订单金额)";
            }
            inOutEntity.RMBMoney = model.money;
            inOutEntity.ModifyManagerId = 0;
            inOutEntity.ModifyTime = DateTime.Now;

            var inoutCashFlag = _inoutCashrepository.Update(inOutEntity);
            if (inoutCashFlag > 0)
            {
                if (inOutEntity.State == 1)
                {
                    #region 风软审核入金逻辑(营业部人员，手工在第三方软件操作 2019-03-04)
                    // 同步风软的审核入金逻辑
                    var rmmfFlag = InCoinRmmfCash(inOutEntity.RmmfUserId.Value, inOutEntity.Money.Value);
                    if (rmmfFlag <= 0)
                    {
                        _logger.LogInformation($"同步风软入金失败！inoutCashID:{ inoutCashFlag }");
                    }
                    #endregion
                }
                _logger.LogInformation($"同步本地数据成功！inoutCashID:{ inoutCashFlag }");
            }
            else
            {
                _logger.LogError($"同步本地数据失败！支付宝/微信/QQ钱包交易单号:{ model.ddh }   支付金额:{ model.money }     支付类型 1支付宝，2QQ钱包，3微信:{model.lb }   网站单号/支付宝备注:{ model.name }   KEY密匙：{ model.key }   支付成功日期：{ model.paytime }");
            }
        }

        /// <summary>
        /// 同步风软的审核入金逻辑
        /// </summary>
        /// <param name="accountId">账户ID</param>
        /// <param name="cashState">类型
        ///     1:现金汇入
        ///     2:现金汇出
        ///     3:在途
        ///     4:转汇
        /// </param>
        /// <param name="amount">数量</param>
        /// <param name="currencyCode">币种</param>
        /// <param name="remark">说明
        ///     银行卡姓名+卡号+银行名称+省份+市。字段间用逗号（，）分隔
        /// </param>
        private int InCoinRmmfCash(int rmmfUserId, decimal amount)
        {
            //USD RMB HKD
            string currencyCode = "USD";
            string remark = "用户入金";
            short cashState = 1;
            decimal absAmount = Math.Abs(amount);
            var allRmmfAccount = _rmmfAccountService.GetActiveAccountInfo();
            var account = allRmmfAccount.FirstOrDefault(p => p.UserID == rmmfUserId);
            if (account == null)
            {
                return 0;
            }
            //_rmmfCashService.AddCashChangeVerifyAsset(accountName, amount, cashState, remark);
            var result = _rmmfCashService.AddCashChange(account.ID, cashState, absAmount, currencyCode, remark);

            return result;
        }

        public BooleanResult GetOrderStateById(int orderId, string ip4, string userId)
        {
            var result = new BooleanResult();

            var entity = _repository.Get($"select * from UCAlipayInCash where UCAlipayInCashId={orderId} ");
            if (entity != null)
            {
                var orderInfo = _payService.GetYunPayOrder(entity.Order, ip4, "1").Result;
                var order = JsonConvert.DeserializeObject<YunPayOrderStateModel>(orderInfo);
                if (order != null)
                {
                    // 订单完成状态(0:等待付款；1:付款完成；2:订单超时；3:订单不存在或者超时被删除；4:token错误)
                    if (order.code != 0)
                    {
                        entity.Code = order.code;
                        entity.Remark = order.msg;
                        entity.ModifyManagerId = userId.ToInt32() ?? 0;
                        entity.ModifyTime = DateTime.Now;
                        if (_repository.Update(entity) > 0)
                        {

                            result.Data = true;
                            result.Success = true;
                            
                            if (order.code == 1)
                            {
                                // 支付成功
                                result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                                result.ResultMsg = entity.Remark; //ResultCodeAddMsgKeys.CommonObjectSuccessMsg;
                            }
                            else
                            {
                                // 支付失败
                                result.ResultCode = ResultCodeAddMsgKeys.AlipayExceptionCode;
                                result.ResultMsg = ResultCodeAddMsgKeys.AlipayExceptionMsg;
                            }
                        }
                        else
                        {
                            result.Data = false;
                            result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                            result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;

                        }
                    }
                    else
                    {
                        // 未完成的订单
                        result.Data = false;
                        result.Success = true;
                        result.ResultCode = ResultCodeAddMsgKeys.CommonObjectSuccessCode;
                        result.ResultMsg = entity.Remark; //ResultCodeAddMsgKeys.CommonObjectSuccessM
                    }
                }
            }
            else
            {
                result.ResultCode = ResultCodeAddMsgKeys.CommonExceptionCode;
                result.ResultMsg = ResultCodeAddMsgKeys.CommonExceptionMsg;
            }

            return result;
        }

        /// <summary>
        /// 获取指定的订单记录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public TableDataModel LoadUnfinishedData(UCAlipayInCashRequestModel model)
        {
            string conditions = "where IsDelete=0 ";// 未删除
            if (!model.Key.IsNullOrWhiteSpace())
            {
                // 订单完成状态(0:等待付款；1:付款完成；2:订单超时；3:订单不存在或者超时被删除；4:token错误)
                conditions += $"and Code in({ model.Key })";
            }
            return new TableDataModel
            {
                count = _repository.RecordCount(conditions),
                data = _repository.GetListPaged(model.Page, model.Limit, conditions, "Id desc"),
            };
        }

        public async Task UpdateUCAlipayInCashState(TableDataModel model)
        {
            // 如果有等待付款的记录
            if (model.count > 0)
            {
                var now = DateTime.Now;
                var list = model.data as IEnumerable<UCAlipayInCash>;
                if (list.Any())
                {
                    _logger.LogInformation($"获取支付宝未完成的订单！");
                    foreach (var item in list)
                    {
                        _logger.LogInformation($"第三方订单状态：{ item.Code }，订单号：{ item.Order }！");
                        // 本地订单未完成或不存在
                        if (item.Code == 0 || item.Code == 3)
                        {
                            var orderInfo = await _payService.GetYunPayOrder(item.Order, item.IP4);
                            _logger.LogInformation($"第三方订单信息：{ orderInfo }！");
                            var order = JsonConvert.DeserializeObject<YunPayOrderStateModel>(orderInfo);
                            if (order != null)
                            {
                                item.Code = order.code;
                                // 如果不是未完成的状态
                                if (order.code != 0)
                                {
                                    item.Code = order.code;
                                    item.Remark = order.msg;
                                    item.ModifyManagerId = 0;
                                    item.ModifyTime = now;
                                    if (_repository.Update(item) > 0)
                                    {
                                        _logger.LogInformation($"同步支付宝订单成功！UCAlipayInCash->ID:{ item.Id }");
                                    }
                                    else
                                    {
                                        _logger.LogInformation($"同步支付宝订单失败！UCAlipayInCash->ID:{ item.Id }");
                                    }
                                    //// 同步
                                    //var inOutCash = _inoutCashrepository.Get(item.UCAlipayInCashId);
                                    //if (inOutCash != null)
                                    //{
                                    //    _repository.Update(item);
                                    //    //// 根据第三方支付状态来更新入金表[UCInOutCash]状态为待审核或入金失败
                                    //    //if (order.code == 1)
                                    //    //{
                                    //    //    inOutCash.State = 0;
                                    //    //}
                                    //    //else
                                    //    //{
                                    //    //    inOutCash.State = 3;
                                    //    //    inOutCash.Remark = "用户入金(支付异常)";
                                    //    //}
                                    //    //inOutCash.ModifyManagerId = 0;
                                    //    //inOutCash.ModifyTime = now;
                                    //    //_inoutCashrepository.Update(inOutCash);
                                    //}
                                }
                            }
                        }
                       
                    }
                }
            }

        }
        
    }
}